#include "lfs.h"

#include <strings.h>
#include <stdio.h>
#include <string.h>
#include <unittest.h>
#include <stddefine.h>
#include <iterator_utils.h>
#include <emalloc.h>
#include <lfs_protocol.h>

#include "master_service.h"

int test_master_service_init(void)
{
    master_service_init();
    {
        FileCreateRequest freq = { "/duoln/index.html", 0, 0 };

        Buffer* fbuf = buffer_new();
        file_create_request_serialize(&freq, fbuf);

        Request req = { MASTER_HANDLER_FILE_CREATE, buffer_get_size(fbuf), buffer_get_data(fbuf) };
        Response resp = { };

        master_service_request(&req, &resp);

        FileCreateResponse fresp = { };
        Buffer* resp_buf = buffer_create(resp.size, resp.data);
        file_create_response_deserialize(resp_buf, &fresp);
    }
    return 1;
}

void test_master_service_file_create()
{
    {
        FileCreateRequest freq =
        { "/duoln/index.html", 2, 3 };

        Buffer* fbuf = buffer_new();
        file_create_request_serialize(&freq, fbuf);

        Request req =
        { MASTER_HANDLER_FILE_CREATE, buffer_get_size(fbuf), buffer_get_data(fbuf) };
        Response resp =
        { };

        master_service_request(&req, &resp);

        FileCreateResponse fresp =
        { };
        Buffer* resp_buf = buffer_create(resp.size, resp.data);
        file_create_response_deserialize(resp_buf, &fresp);

        LEMON_TEST_EQUAL_STRING(lfs_msg(LFS_FILE_IS_EXIST), lfs_msg(fresp.status));
    }
    {
        FileCreateRequest freq =
        { "/duoln/home.html", 0, 0 };

        Buffer* fbuf = buffer_new();
        file_create_request_serialize(&freq, fbuf);

        Request req =
        { MASTER_HANDLER_FILE_CREATE, buffer_get_size(fbuf), buffer_get_data(fbuf) };
        Response resp =
        { };

        master_service_request(&req, &resp);

        FileCreateResponse fresp =
        { };
        Buffer* resp_buf = buffer_create(resp.size, resp.data);
        file_create_response_deserialize(resp_buf, &fresp);

        LEMON_TEST_EQUAL_STRING(lfs_msg(LFS_SUCC), lfs_msg(fresp.status));
    }
    {
        FileCreateRequest freq =
        { "/duoln/us.html", 2, 5 };

        Buffer* fbuf = buffer_new();
        file_create_request_serialize(&freq, fbuf);

        Request req =
        { MASTER_HANDLER_FILE_CREATE, buffer_get_size(fbuf), buffer_get_data(fbuf) };
        Response resp =
        { };

        master_service_request(&req, &resp);

        FileCreateResponse fresp =
        { };
        Buffer* resp_buf = buffer_create(resp.size, resp.data);
        file_create_response_deserialize(resp_buf, &fresp);

        LEMON_TEST_EQUAL_STRING(lfs_msg(LFS_LACK_OF_RESOURCE), lfs_msg(fresp.status));
    }
}

void master_service_add_suite()
{
    UNITTEST_SUITE_INIT();
    UNITTEST_SUITE_SETUP(test_master_service_init);
    UNITTEST_SUITE_CLEANUP(NULL);
    UNITTEST_SUITE_ADD_TESTCASE("test_master_service_file_create", test_master_service_file_create);
}
